// main.go
package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"

	apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
	clientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"
)

func main() {
	// 从环境变量获取配置
	targetCRD := os.Getenv("TARGET_CRD_NAME")
	cleanupPath := os.Getenv("CLEANUP_PATH")

	log.Printf("target CRD: %s", targetCRD)
	// 创建Kubernetes客户端
	config, err := rest.InClusterConfig()
	if err != nil {
		log.Fatalf("Error getting in-cluster config: %v", err)
	}

	client, err := clientset.NewForConfig(config)
	if err != nil {
		log.Fatalf("Error creating clientset: %v", err)
	}

	// 创建CRD Informer
	lw := cache.NewListWatchFromClient(
		client.ApiextensionsV1().RESTClient(),
		"customresourcedefinitions",
		"",
		fields.Everything(),
	)

	_, controller := cache.NewInformer(
		lw,
		&apiextensionsv1.CustomResourceDefinition{},
		0,
		cache.ResourceEventHandlerFuncs{
			DeleteFunc: func(obj interface{}) {
				crd, ok := obj.(*apiextensionsv1.CustomResourceDefinition)
				if !ok {
					log.Println("Deleted object is not a CRD")
					return
				}

				if crd.Name == targetCRD {
					log.Printf("Detected deletion of CRD: %s", targetCRD)

					// 执行清理操作
					if err := os.RemoveAll(cleanupPath); err != nil {
						log.Printf("Error cleaning path %s: %v", cleanupPath, err)
					} else {
						log.Printf("Successfully cleaned path: %s", cleanupPath)
					}
				}
			},
		},
	)

	// 设置信号处理
	stopCh := make(chan struct{})
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigCh
		close(stopCh)
	}()

	// 启动控制器
	log.Println("Starting CRD cleaner controller...")
	controller.Run(stopCh)
	log.Println("Controller stopped")
}
